import { NextRequest, NextResponse } from 'next/server';
import { writeFile, mkdir } from 'fs/promises';
import { existsSync } from 'fs';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';

export const dynamic = 'force-dynamic';

// 添加跨域支持的头部配置
const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};

// 处理预检请求
export async function OPTIONS() {
  return NextResponse.json({}, { headers: corsHeaders });
}

export async function POST(request: NextRequest) {
  console.log('Upload API: 开始处理文件上传');
  try {
    // 解析表单数据
    let formData;
    try {
      formData = await request.formData();
    } catch (formError: any) {
      console.error('Upload API: 解析表单数据失败:', formError);
      return NextResponse.json(
        { error: '无法解析表单数据' },
        { status: 400, headers: corsHeaders }
      );
    }
    
    const file = formData.get('file') as File;
    
    if (!file) {
      console.log('Upload API: 没有找到文件');
      return NextResponse.json(
        { error: '没有找到文件' },
        { status: 400, headers: corsHeaders }
      );
    }

    console.log(`Upload API: 收到文件 ${file.name}, 类型: ${file.type}, 大小: ${file.size} 字节`);

    // 验证文件是否为图片
    const validImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/webp'];
    if (!validImageTypes.includes(file.type)) {
      console.log(`Upload API: 文件类型 ${file.type} 不是有效的图片格式`);
      return NextResponse.json(
        { error: '文件必须是图片格式 (JPEG, PNG, GIF, JPG, WEBP)' },
        { status: 400, headers: corsHeaders }
      );
    }

    // 获取文件扩展名
    const fileExtension = file.name.split('.').pop() || '';
    
    // 创建唯一文件名
    const fileName = `${uuidv4()}.${fileExtension}`;
    console.log(`Upload API: 生成文件名: ${fileName}`);
    
    // 确保目标目录存在
    const uploadsDir = path.join(process.cwd(), 'public', 'assets', 'uploads');
    console.log(`Upload API: 目标目录: ${uploadsDir}`);
    
    if (!existsSync(uploadsDir)) {
      console.log(`Upload API: 目录不存在，正在创建`);
      try {
        await mkdir(uploadsDir, { recursive: true });
      } catch (mkdirError: any) {
        console.error(`Upload API: 创建目录失败:`, mkdirError);
        return NextResponse.json(
          { error: `创建上传目录失败: ${mkdirError.message}` },
          { status: 500, headers: corsHeaders }
        );
      }
    } else {
      console.log(`Upload API: 目录已存在`);
    }
    
    // 文件的完整路径
    const filePath = path.join(uploadsDir, fileName);
    console.log(`Upload API: 文件将保存到: ${filePath}`);
    
    // 将文件内容转换为Buffer并写入文件
    let bytes;
    try {
      bytes = await file.arrayBuffer();
    } catch (arrayBufferError: any) {
      console.error(`Upload API: 读取文件内容失败:`, arrayBufferError);
      return NextResponse.json(
        { error: `读取文件内容失败: ${arrayBufferError.message}` },
        { status: 500, headers: corsHeaders }
      );
    }
    
    const buffer = Buffer.from(bytes);
    console.log(`Upload API: 读取到文件内容，大小: ${buffer.length} 字节`);
    
    // 修复: 使用Uint8Array类型，这是fs.writeFile支持的类型
    try {
      await writeFile(filePath, new Uint8Array(buffer));
      console.log(`Upload API: 文件写入成功`);
    } catch (writeError: any) {
      console.error(`Upload API: 文件写入失败:`, writeError);
      return NextResponse.json(
        { error: `文件写入失败: ${writeError.message}` },
        { status: 500, headers: corsHeaders }
      );
    }
    
    // 构建文件的绝对路径和相对路径
    const absoluteFilePath = path.resolve(filePath);
    const relativePath = `/assets/uploads/${fileName}`;
    
    console.log(`Upload API: 返回路径信息 - 绝对路径: ${absoluteFilePath}, 相对路径: ${relativePath}`);
    
    // 返回成功响应
    return NextResponse.json(
      {
        success: true,
        filePath: absoluteFilePath,
        relativePath: relativePath
      },
      { headers: corsHeaders }
    );
    
  } catch (error: any) {
    console.error('Upload API: 文件上传错误:', error);
    return NextResponse.json(
      { error: `文件上传失败: ${error.message}` },
      { status: 500, headers: corsHeaders }
    );
  }
} 